package com.deworks.admin.common.utils;

import com.deworks.admin.common.constants.ErrorConstants;
import com.deworks.admin.common.exception.AdbException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;

public class AesUtil {

    public static String encrypt(String plainText, String key) {
        byte[] keyByte = Base64Util.decode(key);
        SecretKey secretKey = new SecretKeySpec(keyByte, "AES");
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64Util.encode(cipher.doFinal(plainText.getBytes()));
        } catch (Exception e) {
            throw new AdbException(ErrorConstants.SYSTEM_ERROR_CODE, ErrorConstants.ENCRYPT_ERROR, e);
        }
    }

    public static String decrypt(String cipherText, String key) {
        byte[] keyByte = Base64Util.decode(key);
        SecretKey secretKey = new SecretKeySpec(keyByte, "AES");
        try {
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64Util.decode(cipherText)));
        } catch (Exception e) {
            throw new AdbException(ErrorConstants.SYSTEM_ERROR_CODE, ErrorConstants.DECRYPT_ERROR, e);
        }
    }

    public static String generateKey(int length) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(length);
        byte[] bytes = keyGenerator.generateKey().getEncoded();
        return Base64Util.encode(bytes);
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String key = generateKey(128);
        System.out.println("秘钥：" + key);
        extracted("123456789ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss", key);
        extracted("fasfdsfasrewfsdafass", key);
        extracted("18884107589", key);
        extracted("gfdghdfhrhfhdf", key);
        extracted("eeeeereeeeeeeeeeee", key);

    }

    private static void extracted(String src, String key) {
        String enc = encrypt(src, key);
        System.out.println("秘文：" + enc);
        System.out.println("秘文长度：" + enc.length());

        String dec = decrypt(enc, key);
        System.out.println("原文：" + dec);
    }
}
